package com.example.springbootwebsocket.config;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;


import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: springboot-websocket
 * @description: websocket
 * @author: XianJin.Lu
 * @create: 2021-08-31 14:41
 **/

//外界访问 ws://host:端口/
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class WebSocketEndpoint {
    private Session session;

    //连接建立成功调用的方法
    @OnOpen
    public void  onOpen(Session session, @PathParam("userId") String userId){
    this.session=session;
    //每个客户端的session存起来
    SessionPool.sessions.put(userId, session);

    }


    //移除session  关闭客户端连接
    @OnClose
    public void onClose(Session session) throws IOException {
       SessionPool.remove(session.getId());
       session.close();
    }

    //收到客户端消息后调用的方法
    @OnMessage
    public void  onMessage(Session session,String message){
       //  SessionPool.sendMessage(message);
        Map<String, Object> params = JSON.parseObject(message, new HashMap<String, Object>().getClass());
        SessionPool.sendMessage(params);
    }


}
